﻿using System;
using System.Web.Routing;
using ManagedUIFlow.Infrastructure.Services;
using ManagedUIFlow.Model;

namespace ManagedUIFlow.Infrastructure.Commands
{
    public class SubFlow : ICommand
    {
        private ApplicationController _appController;
        private readonly RequestContext _requestContext;
        private FlowService _flowService;
        private FlowViewServiceBuilder _flowSerializerBuilder;

        public SubFlow(RequestContext requestContext)
        {
            _requestContext = requestContext;            
        }

        public ApplicationController ApplicationController
        {
            get
            {
                return _appController ?? ApplicationController.Current;
            }
            set
            {
                _appController = value;
            }
        }

        public FlowService FlowService
        {
            get
            {
                return _flowService ?? FlowService.Current;
            }
            set { _flowService = value; }
        }

        public FlowViewServiceBuilder FlowSerializerBuilder
        {
            get
            {
                return _flowSerializerBuilder ?? FlowViewServiceBuilder.Current;
            }
            set { _flowSerializerBuilder = value; }
        }

        public void Execute(ManagedFlow flow)
        {
            var flowSerializer = FlowSerializerBuilder.GetFlowViewService();
            var key = flowSerializer.Serialize(flow, _requestContext);
            key += "_" + Guid.NewGuid();
            var flowDefinition = FlowService.GetFlowDefinition(flow.CurrentNavigation);
            if (flowDefinition == null)
                throw new FlowException("Invalid transition.");

            var subFlow = new ManagedFlow(key, flowDefinition.Name, flowDefinition.StartupNavigation, flow.Redirectable,
                                          flow.RedirectUrl) {ConversationData = flow.ConversationData};
            ApplicationController.Execute(_requestContext, subFlow);
        }
    }
}
